import 'package:dio/dio.dart';
import 'package:fsharing/core/models/address.dart';
import 'package:fsharing/core/services/api.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';

/// 地址新建或者更新
class AddressUpdateModel extends ViewModel {
  final Api api;
  final Address address;

  int _id;
  String _linkMan;
  String contactPhone;
  String _verifyCode;
  int _countyId;
  String _provCityCounty;
  String _detailAddress;
  bool _defaulted;
  String _encryptedCode;

  String _errorMessage;

  AddressUpdateModel(this.api, this.address) : super() {
    _id = address?.id;
    _linkMan = address?.linkMan;
    contactPhone = address?.contactPhone;
    _verifyCode = address?.verifyCode;
    _countyId = address?.countyId;
    _provCityCounty = address?.provCityCounty;
    _detailAddress = address?.detailAddress;
    _defaulted = address?.defaulted ?? false;
    _encryptedCode = address?.encryptedCode;
  }

  set linkMan(String value) {
    _linkMan = value;
  }

  set verifyCode(String value) {
    _verifyCode = value;
  }

  int get countyId => _countyId;

  String get provCityCounty => _provCityCounty;

  /// 设置选中的地区
  set mapEntry(MapEntry<String, dynamic> value) {
    _countyId = int.parse(value.key);
    _provCityCounty = value.value;
    notifyListeners();
  }

  set detailAddress(String value) {
    _detailAddress = value;
  }

  bool get defaulted => _defaulted;

  /// 设置默认
  set defaulted(bool value) {
    _defaulted = value;
    notifyListeners();
  }

  set encryptedCode(String value) {
    _encryptedCode = value;
  }

  String get errorMessage => _errorMessage;

  Future<ViewState> addressUpdate() async {
    viewState = ViewState.busy;
    try {
      Address address = Address(
        _id,
        _linkMan,
        contactPhone,
        _verifyCode,
        countyId,
        provCityCounty,
        _detailAddress,
        defaulted,
        _encryptedCode,
      );
      await api.addressUpdate(address);
      viewState = ViewState.success;
    } catch (e) {
      _errorMessage = e is DioError ? e.message : e.toString();
      viewState = ViewState.error;
    }
    return viewState;
  }
}
